package jmu.cze.controller;

import jmu.cze.pojo.Customer;
import jmu.cze.pojo.User;
import jmu.cze.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Resource(name = "userServiceImpl")
    private UserService userService;

    @PostMapping("/doLogin")
    public String doLogin(User user, Model model, HttpSession session){
        User user1 = userService.selectUser(user.getUserID());
        if(user1==null){
            model.addAttribute("msg","改账户不存在");
        }else if(user1.getUserPassword().equals(user.getUserPassword())){
            session.setAttribute("id",user1.getUserID());
            session.setAttribute("permission",user1.getPermission());
            if(user1.getPermission()==1){
                return "redirect:/admin/flight";
            }
            return "redirect:/";
        }else {
            model.addAttribute("msg","密码错误");
        }
        return "user/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }

    @GetMapping("/user/update")
    public String getUpdateInfo(Model model, HttpSession session){
        model.addAttribute("customer",userService.selectCustomer((String) session.getAttribute("id")));
        return "user/update";
    }
    @PostMapping("/user/update")
    public String update(Customer customer, User user, Model model, HttpSession session){
        String userID = (String) session.getAttribute("id");
        user.setUserID(userID);
        customer.setUserID(userID);
        customer.setUser(user);
        if (userService.update(customer)) {
            model.addAttribute("msg"," —— 修改成功");
        }else{
            model.addAttribute("msg", " —— 修改失败");
        }
        model.addAttribute("customer",userService.selectCustomer(userID));
        return "user/update";
    }

    @PostMapping("/user/add")
    public String add(Customer customer, User user,Model model) {
        user.setPermission(0);
        customer.setUser(user);
        customer.setIntegral(0);
        if (userService.insertCustomer(customer)) {
            return "redirect:/login";
        }
        model.addAttribute("msg", " —— 注册失败");
        return "user/register";
    }

    @GetMapping("/user/delete")
    public String delete(HttpSession session){
        String userID = (String) session.getAttribute("id");
        if (userService.deleteUser(userID)) {
            session.invalidate();
            return "redirect:/login";
        }
        return "redirect:/user/update";
    }
}
